import 'dart:io';

import 'package:geolocator/geolocator.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:workmanager/workmanager.dart';
import '../../utils/gps/gps_util.dart';
import '../utils/tool/log_util.dart';
import '../services/gps_service.dart';

@pragma('vm:entry-point')
void callbackDispatcher() {
  Workmanager().executeTask((task, inputData) async {

    print("work manager task start");
   // postLocation({"longitude":"start","latitude":"..."});
    int? totalExecutions;
    final sharedPreference = await SharedPreferences.getInstance(); //Initialize dependency

    try {
      await  GpsUtil.determinePosition().then((p){
        print("坐标${p.longitude} ,${p.latitude}");
        //postLocation({"longitude":p.latitude,"latitude":p.latitude});
      });

      //add code execution
      totalExecutions = sharedPreference.getInt("totalExecutions");
      sharedPreference.setInt("totalExecutions", totalExecutions == null ? 1 : totalExecutions+1);
      print("work manager 执行次数：$totalExecutions");

    } catch(err) {
      print(err.toString()); // Logger flutter package, prints error on the debug console
    //  postLocation({"longitude":err.toString(),"latitude":null});
    }

    return Future.value(true);
  });
}

class WorkManagerConfig{


  void  init(){


    Workmanager().initialize(callbackDispatcher, isInDebugMode: true);

    if(Platform.isIOS) {
      Workmanager().registerOneOffTask(
        "task-identifier",
        "simplePeriodicTask", // Ignored on iOS
        initialDelay: const Duration(minutes: 30),
        constraints: Constraints(
          // connected or metered mark the task as requiring internet
          networkType: NetworkType.connected,
          // require external power
          requiresCharging: true,
        ),
        //   inputData: ... // fully supported
      );
    }

    if(Platform.isAndroid) {
      // Periodic task registration
      Workmanager().registerPeriodicTask(
        "periodic-task-identifier",
        "simplePeriodicTask",
        // When no frequency is provided the default 15 minutes is set.
        // Minimum frequency is 15 min. Android will automatically change your frequency to 15 min if you have configured a lower frequency.
        frequency: const Duration(minutes: 15),
      );
    }



  }
}


WorkManagerConfig workManagerConfig = WorkManagerConfig();
